package com.amqr.movetest.activity;

import android.animation.Animator;
import android.animation.AnimatorInflater;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amqr.movetest.widget.ChildViewPager;
import com.amqr.movetest.widget.FoldView;
import com.amqr.movetest.widget.MyRecyclerLayout;
import com.amqr.movetest.R;
import com.amqr.movetest.bean.SimpleVpBean;

import java.util.ArrayList;
import java.util.List;


/**
 * User: LJM
 * Date&Time: 2017-05-17 & 20:37
 * Describe: Describe Text
 * 添加轮播点
 */
public class VpMultNestingActivity extends AppCompatActivity {

    private ViewPager mVpSimple;
    private List<View> viewList;
    List<SimpleVpBean> simpleVpBeanList;

    private int currentItem;
    private int count;
    private boolean isAutoPlay;
    private Handler handler;
    private int delay = 3000;

    private Animator animatorToLarge;
    private Animator animatorToSmall;


    private SparseBooleanArray isLarge;
    private LinearLayout llDot;


    private int dotSize = 12;
    private int dotSpace = 12;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vp_mult_nesting);
        mVpSimple = (ViewPager) findViewById(R.id.mVpSimple);
        llDot = (LinearLayout) findViewById(R.id.ll_dot);

        getDataSource();
        count = simpleVpBeanList.size();
        fillViewList();

        // 初始化Animator
        initAnimator();

        MyPagerAdapter myPagerAdapter = new MyPagerAdapter(viewList);
        mVpSimple.setAdapter(myPagerAdapter);

        // Viewpager 报The specified child already has a parent. You must call removeView() on the child's parent first.
        // setOffscreenPageLimit(3); 是解决办法
        mVpSimple.setOffscreenPageLimit(3);

        // 从第1张图片开始（位置刚好也是1，注意：0位置现在是最后一张图片）
        currentItem = 1;
        mVpSimple.setCurrentItem(1);

        mVpSimple.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            //这个方法会在屏幕滚动过程中不断被调用。
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            // 哪个页面被选中。当用手指滑动翻页的时候，如果翻动成功了（滑动的距离够长），手指抬起来就会立即执行这个方法
            @Override
            public void onPageSelected(int position) {
                // 遍历一遍子View，设置相应的背景。
                for (int i = 0; i < llDot.getChildCount(); i++) {
                    if (i == position - 1) {// 被选中
                        llDot.getChildAt(i).setBackgroundResource(R.drawable.dot_selected);
                        if (!isLarge.get(i)) {
                            animatorToLarge.setTarget(llDot.getChildAt(i));
                            animatorToLarge.start();
                            isLarge.put(i, true);
                        }
                    } else {// 未被选中
                        llDot.getChildAt(i).setBackgroundResource(R.drawable.dot_unselected);
                        if (isLarge.get(i)) {
                            animatorToSmall.setTarget(llDot.getChildAt(i));
                            animatorToSmall.start();
                            isLarge.put(i, false);
                        }
                    }
                }
            }

            /**
             * 在手指操作屏幕的时候发生变化。有三个值：0（END）,1(PRESS) , 2(UP) 。
             当用手指滑动翻页时，
             手指按下去的时候会触发这个方法，state值为1，
             手指抬起时，如果发生了滑动（即使很小），这个值会变为2，
             然后最后变为0 。总共执行这个方法三次。
             * @param state
             */
            @Override
            public void onPageScrollStateChanged(int state) {
                switch (state) {
                    // 闲置中
                    case ViewPager.SCROLL_STATE_IDLE:
                        Log.d("TTT","fffffffff  vp：SCROLL_STATE_======IDLE");

                        if (mVpSimple.getCurrentItem() == 0) {
                            mVpSimple.setCurrentItem(count, false);
                        } else if (mVpSimple.getCurrentItem() == count + 1) {
                            mVpSimple.setCurrentItem(1, false);
                        }
                        currentItem = mVpSimple.getCurrentItem();
                        isAutoPlay = true;
                        break;
                    // 拖动中
                    case ViewPager.SCROLL_STATE_DRAGGING:
                        Log.d("TTT","fffffffff  vp：SCROLL_STATE_======DRAGGING");
                        isAutoPlay = false;
                        break;
                    // 滑动结束
                    case ViewPager.SCROLL_STATE_SETTLING:
                        Log.d("TTT","fffffffff  vp：SCROLL_STATE_======SETTLING");
                        isAutoPlay = true;
                        break;
                }
            }
        });

        // 设置指示器
        setIndicator();
        //startPlay();
    }

    /**
     * 开始自动播放
     */
    private void startPlay() {
        // 如果少于2张就不用自动播放了
        if (count < 2) {
            isAutoPlay = false;
        } else {
            isAutoPlay = true;
            handler = new Handler();
            handler.postDelayed(task, delay);
        }
    }

    private Runnable task = new Runnable() {
        @Override
        public void run() {
            if (isAutoPlay) {
                // 位置循环
                currentItem = currentItem % (count + 1) + 1;
                // 正常每隔3秒播放一张图片
                mVpSimple.setCurrentItem(currentItem);
                handler.postDelayed(task, delay);
            } else {
                // 如果处于拖拽状态停止自动播放，会每隔5秒检查一次是否可以正常自动播放。
                handler.postDelayed(task, 5000);
            }
        }
    };


    private void initAnimator() {
        animatorToLarge = AnimatorInflater.loadAnimator(this, R.animator.scale_to_large);
        animatorToSmall = AnimatorInflater.loadAnimator(this, R.animator.scale_to_small);
    }


    /**
     * 设置指示器
     */
    private void setIndicator() {
        isLarge = new SparseBooleanArray();
        // 记得创建前先清空数据，否则会受遗留数据的影响。
        llDot.removeAllViews();
        for (int i = 0; i < count; i++) {
            View view = new View(this);
            view.setBackgroundResource(R.drawable.dot_unselected);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(dotSize, dotSize);
            layoutParams.leftMargin = dotSpace / 2;
            layoutParams.rightMargin = dotSpace / 2;
            layoutParams.topMargin = dotSpace / 2;
            layoutParams.bottomMargin = dotSpace / 2;
            llDot.addView(view, layoutParams);
            isLarge.put(i, false);
        }
        llDot.getChildAt(0).setBackgroundResource(R.drawable.dot_selected);
        animatorToLarge.setTarget(llDot.getChildAt(0));
        animatorToLarge.start();
        isLarge.put(0, true);
    }

    // =============
    public class MyPagerAdapter extends PagerAdapter {
        private List<View> viewLists;
        public MyPagerAdapter() {
        }

        public MyPagerAdapter(List<View> viewLists) {
            super();
            this.viewLists = viewLists;
        }

        @Override
        public int getCount() {
            return viewLists.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(viewLists.get(position));
            return viewLists.get(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(viewLists.get(position));
        }
    }
    int preItem = 0;
    private void fillViewList() {
        viewList = new ArrayList<View>();

        for (int i = 0;i<count+2;i++){

            View  view = getLayoutInflater().inflate(R.layout.item_flow_view,null,false);

            final FoldView mFv = (FoldView) view.findViewById(R.id.mFv);
            final MyRecyclerLayout mRvOut = (MyRecyclerLayout) view.findViewById(R.id.mRvOut);
            final ChildViewPager mVpager = (ChildViewPager) view.findViewById(R.id.mVpager);
            TextView mDownT1 = (TextView) view.findViewById(R.id.mDownT1);
            TextView mDownT2 = (TextView) view.findViewById(R.id.mDownT2);

            //mVpager.setIsCanScroll(false);




            mFv.setOpenStateLisner(new FoldView.OpenStateListener() {
                @Override
                public void changeState(boolean state) {
                    if(state){
                        mRvOut.setInterceptState(false);
                        //mVpager.setIsCanScroll(true);


                    }else{
                        mRvOut.setInterceptState(true);
                        //mVpager.setIsCanScroll(false);

                    }
                }

                @Override
                public void releaseState() {

                }
            });

            final ArrayList<View> pageView = new ArrayList<View>();
            //======
            // 获取不同布局文件的View视图
            View view1 = LayoutInflater.from(this).inflate(
                    R.layout.item_vp1, null);
            View view2 = LayoutInflater.from(this).inflate(
                    R.layout.item_vp2, null);

            // 将view装入到一个集合中
            pageView.add(view1);
            pageView.add(view2);


            PagerAdapter pagerAdapter = new PagerAdapter() {
                @Override
                public int getCount() {
                    return pageView.size();
                }

                @Override
                public boolean isViewFromObject(View view, Object object) {
                    return view == object;
                }



                @Override
                public Object instantiateItem(ViewGroup container, int position) {
                    container.addView(pageView.get(position));
                    return pageView.get(position);
                }


                @Override
                public void destroyItem(ViewGroup container, int position, Object object) {
                    container.removeView(pageView.get(position));
                }
            };

            mVpager.setAdapter(pagerAdapter);



            mVpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                }

                @Override
                public void onPageSelected(int position) {
                    Log.d("TTT","子vp：onPageSelected  "+position);
                    if(position == preItem){ // 没有移动
                        return;
                    }

                    if(position>preItem){
                        Log.d("TTT","子vp：下一页");
                        if(position== (pageView.size()-1)){
                            Log.d("TTT","子vp：下一页====");
                        }


                        preItem = position;

                        return;
                    }
                    if(position<preItem){
                        Log.d("TTT","子vp：上一页");
                        if(position== 0){
                            Log.d("TTT","子vp：上一页====");
                        }
                        preItem = position;


                        return;
                    }

                    if(position== 0){

                    }


                }

                @Override
                public void onPageScrollStateChanged(int state) {
                    switch (state) {
                        // 闲置中
                        case ViewPager.SCROLL_STATE_IDLE:
                            Log.d("TTT","子vp：SCROLL_STATE_======IDLE");

                            break;
                        // 拖动中
                        case ViewPager.SCROLL_STATE_DRAGGING:
                            Log.d("TTT","子vp：SCROLL_STATE_======DRAGGING");


                            break;
                        // 滑动结束
                        case ViewPager.SCROLL_STATE_SETTLING:
                            Log.d("TTT","子vp：SCROLL_STATE_======SETTLING");


                            break;

                    }
                }
            });


            //========


            mVpager.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    boolean foldState = mFv.getFoldState();
                    if(foldState){
                        Toast.makeText(VpMultNestingActivity.this,"点击顶部",Toast.LENGTH_SHORT).show();
                    }
                }
            });

            //mVpager.setOffscreenPageLimit(3);

            SimpleVpBean simpleVpBean = null;
            if (i == 0) {// 将最前面一页设置成本来最后的那页
                simpleVpBean = simpleVpBeanList.get(count-1);
            } else if (i == count + 1) {// 将最后面一页设置成本来最前的那页
                simpleVpBean = simpleVpBeanList.get(0);
            } else {
                simpleVpBean = simpleVpBeanList.get(i-1);
            }

            mDownT1.setText(simpleVpBean.top);
            mDownT2.setText(simpleVpBean.bot);

            viewList.add(mFv);
        }

    }

    private void getDataSource() {
        simpleVpBeanList = new ArrayList<>();
        SimpleVpBean simpleVpBean0 = new SimpleVpBean();
        simpleVpBean0.top ="page0";
        simpleVpBean0.bot ="孙悟空";

        SimpleVpBean simpleVpBean1 = new SimpleVpBean();
        simpleVpBean1.top ="page1";
        simpleVpBean1.bot ="路飞";

        SimpleVpBean simpleVpBean2 = new SimpleVpBean();
        simpleVpBean2.top ="page2";
        simpleVpBean2.bot ="马三立";

        simpleVpBeanList.add(simpleVpBean0);
        simpleVpBeanList.add(simpleVpBean1);
        simpleVpBeanList.add(simpleVpBean2);
    }
}
